
#include <BXmlDocument>
#include "member_BXmlDocument.h"

using namespace BWE;

#define member					(*(member_BXmlDocument*)_ptr)
#define member_allocate()		_ptr = new member_BXmlDocument(this)
#define member_release()		delete (member_BXmlDocument*)_ptr

BXmlDocument::BXmlDocument()
{
	member_allocate();
}
BXmlDocument::~BXmlDocument()
{
	member_release();
}

BXmlNode* BXmlDocument::read(const BStream& stream)
{
	BString text;
	char code = 0;
	while (stream.read(code))
	{
		if (text.empty() && code != '<')
			continue;
		text.append(code);
		if (code == '>')
			break;
	}
	if (text.first() != '<' || text.last() != '>')
		return 0;

	BString name;
	int name_end = member.readName(text, 1, name);
	member.root = new BXmlNode(name);

	if (text.endsWith("/>"))
	{
		text.remove(0, name_end);
		text.remove(text.size() - 2);
		member.readAttribs(member.root, text);
	}
	else
	{
		text.remove(0, name_end);
		text.remove(text.size() - 1);
		member.readAttribs(member.root, text);
		member.readNode(member.root, stream);
	}

	return member.root;
}
bool BXmlDocument::write(BStream& stream, BXmlNode* root)
{
	member.text.clear();
	member.writeNode(root, 0);
	return stream.write(member.text.cstr(), member.text.size());
}

BXmlNode* BXmlDocument::root()
{
	return member.root;
}
